package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.UsageRecord
import cn.harry.cabinet.model.enums.OperationType
import cn.harry.cabinet.repository.UsageRecordRepository
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.view.adapter.UsageRecordAdapter
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

/**
 * 使用记录查询页面
 * 支持按工号、姓名、卡号、状态等条件查询
 * 支持删除单条记录和清空所有记录
 */
class UsageRecordFragment : BaseFragment() {

    private lateinit var repository: UsageRecordRepository
    private lateinit var adapter: UsageRecordAdapter

    // UI组件
    private lateinit var searchCard: View
    private lateinit var searchContentLayout: LinearLayout
    private lateinit var etSearch: EditText
    private lateinit var etCardNumber: EditText
    private lateinit var spinnerStatus: Spinner
    private lateinit var btnSearch: Button
    private lateinit var btnReset: Button
    private lateinit var btnDeleteAll: Button
    private lateinit var tvToggleSearch: TextView
    private lateinit var tvTotalCount: TextView
    private lateinit var tvFilteredCount: TextView
    private lateinit var swipeRefreshLayout: androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyView: View
    private lateinit var progressBar: ProgressBar

    // 查询条件
    private var selectedStatus: OperationType? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_usage_record, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        repository = UsageRecordRepository(requireActivity().application)

        initViews(view)
        setupSpinner()
        setupRecyclerView()
        setupListeners()
        setupEmptyState()

        loadInitialData()
    }
    
    private fun setupEmptyState() {
        // 自定义空状态的图标和文字
        emptyView.findViewById<ImageView>(R.id.emptyStateIcon)?.apply {
            setImageResource(R.drawable.ic_settings)
        }
        emptyView.findViewById<TextView>(R.id.emptyStateTitle)?.text = "暂无使用记录"
        emptyView.findViewById<TextView>(R.id.emptyStateMessage)?.text = "请调整查询条件后重试"
    }
    
    /**
     * 重写主题应用方法，确保主题切换时正确更新UI
     */
    override fun applyThemeToFragment() {
        super.applyThemeToFragment()
        
        view?.let { fragmentView ->
            try {
                val currentTheme = getCurrentTheme()
                val themeColors = cn.harry.cabinet.theme.manager.ThemeManager.getThemeColors(currentTheme)
                
                // 更新背景颜色
                fragmentView.setBackgroundColor(
                    androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.background)
                )
                
                // 更新文本颜色
                updateTextColors(themeColors)
                
            } catch (e: Exception) {
                android.util.Log.w("UsageRecordFragment", "Failed to apply theme: ${e.message}")
            }
        }
    }
    
    /**
     * 更新文本颜色以匹配主题
     */
    private fun updateTextColors(themeColors: cn.harry.cabinet.theme.manager.ThemeManager.ThemeColors) {
        try {
            val secondaryColor = androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.onSurfaceVariant)
            val accentColor = androidx.core.content.ContextCompat.getColor(requireContext(), themeColors.primary)
            
            tvTotalCount.setTextColor(secondaryColor)
            tvFilteredCount.setTextColor(secondaryColor)
            tvToggleSearch.setTextColor(accentColor)
            
        } catch (e: Exception) {
            android.util.Log.w("UsageRecordFragment", "Failed to update text colors: ${e.message}")
        }
    }

    private fun initViews(view: View) {
        searchCard = view.findViewById(R.id.searchCard)
        searchContentLayout = view.findViewById(R.id.searchContentLayout)
        etSearch = view.findViewById(R.id.etSearch)
        etCardNumber = view.findViewById(R.id.etCardNumber)
        spinnerStatus = view.findViewById(R.id.spinnerStatus)
        btnSearch = view.findViewById(R.id.btnSearch)
        btnReset = view.findViewById(R.id.btnReset)
        btnDeleteAll = view.findViewById(R.id.btnDeleteAll)
        tvToggleSearch = view.findViewById(R.id.tvToggleSearch)
        
        // 统计信息需要从 include 布局中获取
        val statsLayout = view.findViewById<View>(R.id.statsLayout)
        tvTotalCount = statsLayout.findViewById(R.id.tvTotalCount)
        tvFilteredCount = statsLayout.findViewById(R.id.tvFilteredCount)
        
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout)
        recyclerView = view.findViewById(R.id.recyclerViewRecords)
        emptyView = view.findViewById(R.id.emptyView)
        progressBar = view.findViewById(R.id.progressBar)
    }

    private fun setupSpinner() {
        // 状态下拉框
        val statuses = listOf(
            "全部" to null,
            "取出" to OperationType.RETRIEVE,
            "归还" to OperationType.STORE
        )

        val statusAdapter = ArrayAdapter(
            requireContext(),
            R.layout.spinner_item_light,
            statuses.map { it.first }
        )
        statusAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item_light)
        spinnerStatus.adapter = statusAdapter

        spinnerStatus.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                selectedStatus = statuses[position].second
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                selectedStatus = null
            }
        }
    }

    private fun setupRecyclerView() {
        adapter = UsageRecordAdapter(
            onItemClick = { record -> showRecordDetail(record) },
            onDeleteClick = { record -> confirmDelete(record) }
        )

        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter
    }

    private fun setupListeners() {
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener {
            performSearch()
        }

        // 查询按钮
        btnSearch.setOnClickListener {
            performSearch()
        }

        // 重置按钮
        btnReset.setOnClickListener {
            resetFilters()
        }

        // 清空所有记录按钮
        btnDeleteAll.setOnClickListener {
            confirmDeleteAll()
        }

        // 展开/收起查询条件
        tvToggleSearch.setOnClickListener {
            toggleSearchCard()
        }
    }

    private fun toggleSearchCard() {
        val isExpanded = searchCard.visibility == View.VISIBLE
        if (isExpanded) {
            // 收起：隐藏查询卡片
            searchCard.visibility = View.GONE
            tvToggleSearch.text = "展开 ▼"
        } else {
            // 展开：显示查询卡片
            searchCard.visibility = View.VISIBLE
            tvToggleSearch.text = "收起 ▲"
        }
    }

    private fun loadInitialData() {
        performSearch()
        loadTotalCount()
    }

    private fun performSearch() {
        progressBar.visibility = View.VISIBLE

        lifecycleScope.launch {
            try {
                val searchText = etSearch.text.toString().trim()
                val cardNumber = etCardNumber.text.toString().trim()
                
                val records = repository.searchRecords(
                    employeeId = if (searchText.isNotEmpty()) searchText else null,
                    name = if (searchText.isNotEmpty()) searchText else null,
                    cardNumber = if (cardNumber.isNotEmpty()) cardNumber else null,
                    status = selectedStatus,
                    startTime = null,
                    endTime = null
                )

                adapter.setRecords(records)
                updateUI(records)
            } catch (e: Exception) {
                showToast("查询失败: ${e.message}")
            } finally {
                progressBar.visibility = View.GONE
            }
        }
    }

    private fun loadTotalCount() {
        lifecycleScope.launch {
            try {
                val count = repository.getCount()
                tvTotalCount.text = "总数: $count"
            } catch (e: Exception) {
                // Ignore
            }
        }
    }

    private fun resetFilters() {
        etSearch.text.clear()
        etCardNumber.text.clear()
        spinnerStatus.setSelection(0)

        performSearch()
    }

    private fun updateUI(records: List<UsageRecord>) {
        // 停止刷新动画
        swipeRefreshLayout.isRefreshing = false
        
        if (records.isEmpty()) {
            recyclerView.visibility = View.GONE
            emptyView.visibility = View.VISIBLE
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyView.visibility = View.GONE
        }

        tvFilteredCount.text = "筛选结果: ${records.size}"
    }

    private fun showRecordDetail(record: UsageRecord) {
        val dateTimeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        
        val message = buildString {
            append("姓名: ${record.name}\n")
            append("工号: ${record.employeeId}\n")
            record.cardNumber?.let { append("卡号: $it\n") }
            append("状态: ${getStatusText(record.status)}\n")
            record.takeTime?.let { append("取出时间: ${dateTimeFormat.format(it)}\n") }
            record.returnTime?.let { append("归还时间: ${dateTimeFormat.format(it)}\n") }
            
            if (record.takeTime != null && record.returnTime != null) {
                val duration = record.returnTime.time - record.takeTime.time
                append("使用时长: ${formatDuration(duration)}")
            }
        }

        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("记录详情")
            .setMessage(message)
            .setPositiveButton("确定", null)
            .show()
    }

    private fun confirmDelete(record: UsageRecord) {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("确认删除")
            .setMessage("确定要删除 ${record.name} 的使用记录吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteRecord(record)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteRecord(record: UsageRecord) {
        lifecycleScope.launch {
            try {
                repository.delete(record)
                adapter.removeRecord(record)
                showToast("删除成功")
                loadTotalCount()
                
                // 记录删除日志
                val dateTimeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "USAGE_RECORD_DELETE",
                    description = "删除使用记录: ${record.name}",
                    oldValue = "姓名: ${record.name}, 工号: ${record.employeeId}, 状态: ${getStatusText(record.status)}",
                    newValue = "已删除"
                )
                
                // 更新UI
                val currentRecords = adapter.getRecords()
                updateUI(currentRecords)
            } catch (e: Exception) {
                showToast("删除失败: ${e.message}")
                
                // 记录删除失败日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "USAGE_RECORD_DELETE",
                    description = "删除使用记录失败: ${record.name}",
                    oldValue = "姓名: ${record.name}, 工号: ${record.employeeId}",
                    newValue = "删除失败: ${e.message}"
                )
            }
        }
    }

    private fun confirmDeleteAll() {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("确认清空")
            .setMessage("确定要清空所有使用记录吗？此操作不可恢复！")
            .setPositiveButton("清空") { _, _ ->
                deleteAllRecords()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteAllRecords() {
        lifecycleScope.launch {
            try {
                // 获取当前记录数
                val count = repository.getCount()
                
                repository.deleteAll()
                adapter.setRecords(emptyList())
                showToast("已清空所有记录")
                loadTotalCount()
                updateUI(emptyList())
                
                // 记录清空日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "USAGE_RECORD_CLEAR",
                    description = "清空所有使用记录",
                    oldValue = "记录数: $count",
                    newValue = "已清空"
                )
            } catch (e: Exception) {
                showToast("清空失败: ${e.message}")
                
                // 记录清空失败日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "USAGE_RECORD_CLEAR",
                    description = "清空使用记录失败",
                    oldValue = "",
                    newValue = "清空失败: ${e.message}"
                )
            }
        }
    }

    private fun getStatusText(status: OperationType): String {
        return when (status) {
            OperationType.RETRIEVE -> "取出"
            OperationType.STORE -> "归还"
            else -> "未知"
        }
    }
    
    private fun formatDuration(durationMillis: Long): String {
        val seconds = durationMillis / 1000
        val minutes = seconds / 60
        val hours = minutes / 60
        val days = hours / 24
        
        return when {
            days > 0 -> "${days}天${hours % 24}小时"
            hours > 0 -> "${hours}小时${minutes % 60}分钟"
            minutes > 0 -> "${minutes}分钟${seconds % 60}秒"
            else -> "${seconds}秒"
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }
}